package com.itheima.myiotest1;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test1 {
    public static void main(String[] args) throws IOException {
        //1.定义网址数据
        //String s1="";
        String familyNameNet = "http://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1173ee1b0d&from=kg0";
        String boyNameNet = "http://www.haoming8.cn/baobao/10881.html";
        String girlNameNet = "http://www.haoming8.cn/baobao/7641.html";

        //2.获取数据
        //String familyNameStr = webCrawer(familyNameNet);
        String boyNameStr = webCrawer(boyNameNet);
        //String girlNameStr = webCrawer(girlNameNet);

        //System.out.println(girlNameNet);
        //3.通过正则表达式将数据进行写出
        ArrayList<String> familyNameTempList = getData(boyNameStr, "(.{4})(，|。)", 1);
        System.out.println(familyNameTempList);
    }

    private static ArrayList<String> getData(String str, String regex, int index) {
        ArrayList<String> list = new ArrayList<>();
        //创建pattern的对象
        Pattern compile = Pattern.compile(regex);
        //按照pattern的规则到str中获取对象
        Matcher matcher = compile.matcher(str);
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list;
    }
    //

    //定义方法读取数据
    public static String webCrawer(String net) throws IOException {
        //定义容器
        StringBuilder sb = new StringBuilder();
        //定义网址
        URL url = new URL(net);
        //进行连接
        URLConnection conn = url.openConnection();
        //将字符流装换成字节流
        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
        //开始读取数据
        int ch;
        while ((ch = isr.read()) != -1) {
            sb.append((char) ch);
        }
        //进行关流
        isr.close();
        return sb.toString();
    }
}
